﻿using Stote.Helpers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Stote.Forms
{
    public partial class FrmStore : Form
    {
        Dong.BLL.Store storeBLL = new Dong.BLL.Store();

        #region 构造函数
        public FrmStore()
        {
            InitializeComponent();
            Bind();

            btnSearch.Click += btnSearch_Click;
            btnAdd.Click += btnAdd_Click;
            ucPager1.PageChanged += UcPager1_PageChanged;
            dataGridView1.CellPainting += dataGridView1_CellPainting;
            dataGridView1.CellMouseClick += dataGridView1_CellMouseClick;
            dataGridView1.CellFormatting += dataGridView1_CellFormatting;
        }

        #endregion

        #region 数据绑定
        private void Bind()
        {
            List<Dong.Model.Status> list = new List<Dong.Model.Status>() {
                new Dong.Model.Status(){Id=-1,Name="全部"},
                new Dong.Model.Status(){Id=0,Name="正常"},
                new Dong.Model.Status(){Id=1,Name="禁用"},
            };
            cbStatus.DataSource = list;
            cbStatus.DisplayMember = "Name";
            cbStatus.ValueMember = "Id";
        }
        #endregion

        #region 打开添加窗体
        private void btnAdd_Click(object sender, EventArgs e)
        {
            FrmStoreAddAndEdit form = new FrmStoreAddAndEdit(0, this);
            if (form.ShowDialog() == DialogResult.OK)
            {
                btnSearch.PerformClick();
            }
        }
        #endregion

        #region 查询及数据绑定
        private void UcPager1_PageChanged(int pageSize, int currentPage, out int totalCount)
        {
            int startIndex = (currentPage - 1) * pageSize + 1;
            int endIndex = startIndex + pageSize - 1;
            string strWhere = $" 1=1";
            if (!string.IsNullOrEmpty(txtStoreName.Text.Trim()))
                strWhere += $" AND StoreName LIKE '%{txtStoreName.Text.Trim()}%'";
           
            if (Convert.ToInt32(cbStatus.SelectedValue) != -1)
                strWhere += $" AND Status={Convert.ToInt32(cbStatus.SelectedValue)}";

            DataSet ds = storeBLL.GetListByPage(strWhere, "CreateTime DESC", startIndex, endIndex);

            totalCount = storeBLL.GetRecordCount(strWhere);
            dataGridView1.DataSource = ds.Tables[0];

            DataGridViewHelper.DataGridStyle(dataGridView1);

            dataGridView1.Columns["Row"].Visible = false;
            dataGridView1.Columns["StorePlace"].Visible = false;
            dataGridView1.Columns["Remark"].Visible = false;
            dataGridView1.Columns["Status"].Visible = false;
            dataGridView1.Columns["CreateUserId"].Visible = false;
            dataGridView1.Columns["LastUpdateUserId"].Visible = false;

            dataGridView1.Columns["StoreId"].HeaderText = "主键";
            dataGridView1.Columns["StoreName"].HeaderText = "仓库名称";
            dataGridView1.Columns["StorePlace"].HeaderText = "仓库位置";
            dataGridView1.Columns["AreaCount"].HeaderText = "分区数量";
            dataGridView1.Columns["Remark"].HeaderText = "备注";
            dataGridView1.Columns["Status"].HeaderText = "状态";
            dataGridView1.Columns["StatusName"].HeaderText = "状态";
            dataGridView1.Columns["CreateUserId"].HeaderText = "创建人Id";
            dataGridView1.Columns["CreateUserName"].HeaderText = "创建人";
            dataGridView1.Columns["CreateTime"].HeaderText = "创建时间";
            dataGridView1.Columns["LastUpdateUserId"].HeaderText = "修改人Id";
            dataGridView1.Columns["LastUpdateUserName"].HeaderText = "修改人";
            dataGridView1.Columns["LastUpdateTime"].HeaderText = "修改时间";

            dataGridView1.Columns["CreateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            dataGridView1.Columns["LastUpdateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";

            if (!dataGridView1.Columns.Contains("Operator"))
            {
                dataGridView1.Columns.Add("Operator", "操作");
                dataGridView1.Columns["CreateUserName"].Width = 90;
                dataGridView1.Columns["CreateTime"].Width = 220;
                dataGridView1.Columns["LastUpdateUserName"].Width = 90;
                dataGridView1.Columns["LastUpdateTime"].Width = 220;
                dataGridView1.Columns["Operator"].Width = 160;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ucPager1.CurrentPage = 1;
            ucPager1.TriggerPageChanged();
        }
        #endregion

        #region 网格添加列，格式化
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    StringFormat sf = StringFormat.GenericDefault.Clone() as StringFormat;
                    sf.FormatFlags = StringFormatFlags.DisplayFormatControl;
                    sf.Alignment = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Trimming = StringTrimming.EllipsisCharacter;

                    e.PaintBackground(e.CellBounds, false);

                    Font myFont = new Font("微软雅黑", 10F, FontStyle.Underline, GraphicsUnit.Point, 134);
                    SizeF sizeSta = e.Graphics.MeasureString("启用", myFont);
                    SizeF sizeDel = e.Graphics.MeasureString("删除", myFont);
                    SizeF sizeMod = e.Graphics.MeasureString("编辑", myFont);
                    float totalWidth = (sizeSta.Width + sizeDel.Width + sizeMod.Width);

                    float fSta = sizeSta.Width / totalWidth;
                    float fDel = sizeDel.Width / totalWidth;
                    float fMod = sizeMod.Width / totalWidth;

                    var rect1 = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fSta, e.CellBounds.Height);
                    var rect2 = new RectangleF(rect1.Right, e.CellBounds.Top, e.CellBounds.Width * fDel, e.CellBounds.Height);
                    var rect3 = new RectangleF(rect2.Right, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);

                    e.Graphics.DrawString("启用", myFont, new SolidBrush(Color.FromArgb(1, 62, 153)), rect1, sf);
                    e.Graphics.DrawString("删除", myFont, Brushes.Red, rect2, sf);
                    e.Graphics.DrawString("编辑", myFont, new SolidBrush(Color.FromArgb(1, 62, 153)), rect3, sf);

                    e.Handled = true;
                }
            }
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;
                if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    Graphics g = dataGridView1.CreateGraphics();
                    Font myFont = new Font("微软雅黑", 10F, FontStyle.Underline, GraphicsUnit.Point, 134);

                    SizeF sizeSta = g.MeasureString("启用", myFont);
                    SizeF sizeDel = g.MeasureString("删除", myFont);
                    SizeF sizeMod = g.MeasureString("编辑", myFont);
                    float totalWidth = (sizeSta.Width + sizeDel.Width + sizeMod.Width);

                    float fSta = sizeSta.Width / totalWidth;
                    float fDel = sizeDel.Width / totalWidth;
                    float fMod = sizeMod.Width / totalWidth;

                    var rectTotal = new Rectangle(0, 0, dataGridView1.Columns[e.ColumnIndex].Width, dataGridView1.Rows[e.RowIndex].Height);
                    var rectSta = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * fSta, rectTotal.Height);
                    var rectDel = new RectangleF(rectSta.Right, rectTotal.Top, rectTotal.Width * fDel, rectTotal.Height);
                    var rectMod = new RectangleF(rectDel.Right, rectTotal.Top, rectTotal.Width * fMod, rectTotal.Height);

                    int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["StoreId"].Value);
                    Dong.Model.Store model = storeBLL.GetModel(id);

                    if (rectSta.Contains(curPosition))
                    {
                        if (model.Status == 0)
                        {
                            MessageBox.Show("数据正常，不必再次启用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        DialogResult dr = MessageBox.Show("你确定要启用此条记录吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            model.Status = 0;
                            model.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                            model.LastUpdateTime = DateTime.Now;
                            storeBLL.Update(model);
                            btnSearch.PerformClick();
                        }
                    }

                    if (rectDel.Contains(curPosition))
                    {
                        if (model.Status == 1)
                        {
                            MessageBox.Show("已禁用的数据，不必再次删除！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        DialogResult dr = MessageBox.Show("你确定要删除此条记录吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            model.Status = 1;
                            model.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                            model.LastUpdateTime = DateTime.Now;
                            storeBLL.Update(model);
                            btnSearch.PerformClick();
                        }
                    }

                    if (rectMod.Contains(curPosition))
                    {
                        if (model.Status == 1)
                        {
                            MessageBox.Show("禁用的数据不能编辑！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        FrmStoreAddAndEdit form = new FrmStoreAddAndEdit(id, this);
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            btnSearch.PerformClick();
                        }
                    }
                }
            }
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("StatusName"))
            {
                if (e.Value.ToString() == "正常")
                {
                    e.CellStyle.ForeColor = Color.FromArgb(1, 62, 153);
                }
                else
                {
                    e.CellStyle.ForeColor = Color.Red;
                }
            }
        }
        #endregion
    }
}
